package com.atguigu.spzx.manager.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.atguigu.spzx.common.utils.BeanUtils;
import com.atguigu.spzx.manager.entity.Category;
import com.atguigu.spzx.manager.mapper.CategoryMapper;
import com.atguigu.spzx.manager.vo.category.CategoryImportExcelVo;

import java.util.List;

/**
 * <p>
 * ExcelListener
 * </p>
 *
 * @author flyduck
 * @since 2023/10/29
 */
public class ExcelListener<T> implements ReadListener<T> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理List ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;

    /**
     * 缓存的数据
     */
    private List<T> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    //有个很重要的点 DemoDataListener 不能被spring管理，
    //通过构造器传mapper,进行数据库操作
    private CategoryMapper categoryMapper;

    public ExcelListener(CategoryMapper categoryMapper){
        this.categoryMapper = categoryMapper;
    }

    //读取excel内容
    //会从第二行开始读取，把每行数据封装到t对象里面
    @Override
    public void invoke(T data, AnalysisContext context) {
        //把每行数据放到list里面去
        cachedDataList.add(data);
        //达到BATCH COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易00M
        if(cachedDataList.size() >= BATCH_COUNT){
            //调用方法添加到数据库
            saveData();
            //清理list数据
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }


    //所有操作完成后执行
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        //如果达不到100行，invoke方法就不会保存到数据库
        saveData();
    }

    //批量保存
    private void saveData() {
        List<Category> categoryList = BeanUtils.toBeanList((List<CategoryImportExcelVo>) cachedDataList, Category.class);
        categoryMapper.insertList(categoryList);
    }

}
